﻿const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

// 模拟用户数据库
const users = new Map();
const JWT_SECRET = 'your-secret-key'; // 实际应用中应该使用环境变量

// 注册路由
router.post('/register', async (req, res) => {
    try {
        const { username, password, email } = req.body;

        // 验证输入
        if (!username || !password || !email) {
            return res.status(400).json({ error: '所有字段都是必填的' });
        }

        // 检查用户是否已存在
        if (Array.from(users.values()).some(user => user.email === email)) {
            return res.status(400).json({ error: '该邮箱已被注册' });
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10);

        // 创建新用户
        const newUser = {
            id: Date.now().toString(),
            username,
            email,
            password: hashedPassword,
            avatar: `https://api.multiavatar.com/${username}.png`
        };

        users.set(newUser.id, newUser);

        // 生成 JWT
        const token = jwt.sign({ userId: newUser.id }, JWT_SECRET, { expiresIn: '24h' });

        res.status(201).json({
            token,
            user: {
                id: newUser.id,
                username: newUser.username,
                email: newUser.email,
                avatar: newUser.avatar
            }
        });
    } catch (error) {
        res.status(500).json({ error: '注册失败', details: error.message });
    }
});

// 登录路由
router.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;

        // 查找用户
        const user = Array.from(users.values()).find(u => u.email === email);
        if (!user) {
            return res.status(401).json({ error: '用户名或密码错误' });
        }

        // 验证密码
        const isValidPassword = await bcrypt.compare(password, user.password);
        if (!isValidPassword) {
            return res.status(401).json({ error: '用户名或密码错误' });
        }

        // 生成 JWT
        const token = jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '24h' });

        res.json({
            token,
            user: {
                id: user.id,
                username: user.username,
                email: user.email,
                avatar: user.avatar
            }
        });
    } catch (error) {
        res.status(500).json({ error: '登录失败', details: error.message });
    }
});

// 验证中间件
const authMiddleware = (req, res, next) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];
        if (!token) {
            return res.status(401).json({ error: '未授权' });
        }

        const decoded = jwt.verify(token, JWT_SECRET);
        req.userId = decoded.userId;
        next();
    } catch (error) {
        res.status(401).json({ error: '无效的令牌' });
    }
};

// 获取当前用户信息
router.get('/me', authMiddleware, (req, res) => {
    const user = users.get(req.userId);
    if (!user) {
        return res.status(404).json({ error: '用户不存在' });
    }

    res.json({
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar
    });
});

module.exports = { router, authMiddleware }; 